package com.rpi.action;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;

public final class GpioListener implements GpioPinListenerDigital {

	private static Logger log = LoggerFactory.getLogger(GpioListener.class);

	private boolean actionOnHigh;
	private IGpioAction gpioAction;
	private int timeout;

	private long lastActionDone = 0;

	public GpioListener(IGpioAction action, boolean actionOnHigh, int timeoutMs) {
		this.actionOnHigh = actionOnHigh;
		this.gpioAction = action;
		this.timeout = timeoutMs;
	}

	public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
		if (lastActionDone == 0 || (System.nanoTime() > lastActionDone + (timeout * 1000000)) ) {
			log.info("pin {} state changed to {}.", event.getPin().getName(), event.getState().getName());

			if ((event.getState().isHigh() && actionOnHigh) || (event.getState().isLow() && !actionOnHigh)) {
				log.debug("Invoking action");
				gpioAction.action();
			} else {
				log.debug("Invoking actionDone");
				gpioAction.actionDone();
				lastActionDone = System.nanoTime();
			}
		}
	}
}
